<template>
  <div class="alarm-container">
    <el-row :gutter="10" style="margin: 0 16px">
      <el-col :span="12" v-for="(item, index) in alarmList" :key="index">
        <div class="alarm-item" @click="clickVisibleImgae(item)" style="cursor: pointer; width: 100%">
          <img :src="domain + item.img_name" />
          <div class="item-tips">
            <span style="font-weight: bold">告警类型：</span>{{ item.algorithm_name }}
          </div>
          <div class="item-tips">
            <span style="font-weight: bold">告警时间：</span>{{ item.alarm_dt }}
          </div>
          <div class="item-tips">
            <span style="font-weight: bold">告警状态：</span>{{ item.state == 1 ? '正常' : '误检' }}
            <el-button class="state-btn" @click.stop="clickFeedback(item)" v-if="item.state == 1"
              size="mini">反馈</el-button>
          </div>
          <div class="item-tips">
            <span style="font-weight: bold">摄像头位置：</span>{{ item.camera_name }}
          </div>
          <div class="item-tips" v-if="item.deptName">
            <span style="font-weight: bold">船舶名称：</span>{{ item.deptName }}
          </div>
          <div @click.stop="clickVideo(item)" class="popup-video">查看视频（视频为告警时间前后5秒）</div>
        </div>
      </el-col>
    </el-row>
    <!-- 高级弹窗 -->
    <el-dialog title="告警列表" width="80%" :visible.sync="dialogTableVisible">
      <div class="alarm-select">
        <el-date-picker v-model="select.date" type="datetimerange" :picker-options="pickerOptions" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']"
          value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" style="width: 400px">
        </el-date-picker>
        <el-button type="primary" icon="el-icon-search" style="margin-left: 10px" @click="getALarmList">查询</el-button>
      </div>
      <div class="alarm-popup">
        <div class="popup-item" v-for="(item, index) in alarmPopupList" :key="index" @click="clickVisibleImgae(item)"
          style="cursor: pointer">
          <img :src="domain + item.img_name" />
          <div class="popup-title">
            告警类型:
            <span style="color: red">{{ item.algorithm_name }}</span>
          </div>
          <div class="popup-tips">
            <span style="font-weight: bold; color: #333">告警时间：</span>{{ item.alarm_dt }}
          </div>
          <div class="popup-tips">
            <span style="font-weight: bold; color: #333">告警状态：</span>{{ item.state == 1 ? '正常' : '误检' }}
            <el-button class="state-btn" @click.stop="clickFeedback(item)" v-if="item.state == 1"
              size="mini">反馈</el-button>
          </div>
          <div class="popup-tips">
            <span style="font-weight: bold; color: #333">摄像头位置：</span>{{ item.camera_name }}
          </div>
          <div class="popup-tips" v-if="item.deptName">
            <span style="font-weight: bold; color: #333">船舶名称：</span>{{ item.deptName }}
          </div>
          <div @click.stop="clickVideo(item)" class="popup-video">查看视频（视频为告警时间前后5秒）</div>
        </div>
      </div>
    </el-dialog>
    <!-- 查看图片 -->
    <el-image-viewer :on-close="
        () => {
          dialogImageShow = false;
        }
      " style="z-index: 99999" v-if="dialogImageShow" :url-list="[imgUrl]" />

    <el-dialog title="告警信息" width="840px" :visible.sync="dialogImgaeVisible">
      <MarkDetail :alarmInfo="alarmInfo" :fileUrl="imageBase64" :filePath="filePath" :dataList="boxList" :ratio="1"
        :dataListAll="roiList" pageType="detail" />
    </el-dialog>
    <!-- 反馈popup -->
    <el-dialog title="一键反馈" width="800px" :visible.sync="feedbackVisible">
      <el-form :model="feedbackForm" label-width="80px">
        <el-form-item label="状态">
          <el-select v-model="feedbackForm.state" style="width: 100%;" placeholder="请选择状态">
            <el-option label="正常" value="1"></el-option>
            <el-option label="误检" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" :rows="4" v-model="feedbackForm.remark" placeholder="请输入备注"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="feedbackVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm()">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import ElImageViewer from "element-ui/packages/image/src/image-viewer";
  import MarkDetail from "../common/markDetail.vue";
  export default {
    name: "alarm",
    components: {
      ElImageViewer,
      MarkDetail,
    },
    data() {
      return {
        filePath: {},
        alarmInfo: {},
        feedbackForm: {
          id: '',
          state: '2',
          remark: '',
        },
        feedbackVisible: false, //反馈popup
        domain: JSON.parse(localStorage.getItem("userInfo")).domain + "/wvp/",
        videoDomain: JSON.parse(localStorage.getItem("userInfo")).domain + "/wvp-video/",
        imageBase64: "",
        dialogImgaeVisible: false,
        boxList: [],
        roiList: [],
        intervalShow: false,
        tispShow: false,
        quantityNum: 0,
        alarmList: [],
        dialogTableVisible: false,
        alarmPopupList: [],
        select: {
          page: 1,
          count: 8,
          total: 0,
          date: [],
        },
        dialogImageShow: false,
        imgUrl: "",
        pickerOptions: {
          shortcuts: [
            {
              text: "最近一周",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit("pick", [start, end]);
              },
            },
            {
              text: "最近一个月",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit("pick", [start, end]);
              },
            },
            {
              text: "最近三个月",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                picker.$emit("pick", [start, end]);
              },
            },
            {
              text: "最近一年",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
                picker.$emit("pick", [start, end]);
              },
            },
          ],
        },
      };
    },
    mounted() {
      const that = this;
      // 获取当前年月日
      this.select.date[0] =
        new Date()
          .toLocaleDateString("zh-CN", {
            year: "numeric",
            month: "2-digit",
            day: "2-digit",
          })
          .replace(/\//g, "-") + " 00:00:00";

      this.select.date[1] =
        new Date()
          .toLocaleDateString("zh-CN", {
            year: "numeric",
            month: "2-digit",
            day: "2-digit",
          })
          .replace(/\//g, "-") + " 23:59:59";

      this.getToday();
      this.getLatest();
      this.getALarmList();
      that.intervalId = setInterval(() => {
        that.getToday();
      }, 5000);
      setTimeout(() => {
        that.intervalShow = true;
      }, 500);
    },
    methods: {
      clickFeedback(item) {
        this.feedbackForm.id = item.id;
        this.feedbackForm.remark = '';
        this.feedbackForm.state = '2';
        this.feedbackVisible = true;
      },
      // 反馈弹窗确定按钮
      submitForm() {
        const that = this;
        that
          .$axios({
            method: "get",
            url: `/api/message/update-state?id=${that.feedbackForm.id}&state=${that.feedbackForm.state}&remark=${that.feedbackForm.remark}`,
          })
          .then((res) => {
            if (res.data.code == 0) {
              that.$message.success("反馈成功!");
              setTimeout(() => {
                that.getLatest();
                that.getALarmList();
              }, 500);
            }
            that.feedbackVisible = false;
          });
        console.log(that.feedbackForm)
      },
      // 查看视频
      clickVideo(item) {
        const that = this;
        if (item.filePath === '' || item.filePath == null) {
          this.$message.error("暂无视频!");
          return
        }
        window.open(this.videoDomain + item.filePath, "_blank");
        return
        // 定义初始时间
        const initialTime = new Date(item.alarm_dt);

        // 获取前后5秒的时间
        const beforeTime = new Date(initialTime.getTime() - 4000); // 减去4000毫秒
        const afterTime = new Date(initialTime.getTime() + 4000); // 加上4000毫秒

        // 格式化时间
        const formatTime = (date) => {
          const pad = (num) => (num < 10 ? "0" + num : num);
          return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(
            date.getDate()
          )} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(
            date.getSeconds()
          )}`;
        };
        let startTime = formatTime(beforeTime);
        let endTime = formatTime(afterTime);
        that
          .$axios({
            method: "get",
            url: `/api/department/box/channel?boxId=${item.box_id}&name=${item.camera_name}`,
          })
          .then((res) => {
            if (res.data.data == null) {
              this.$message.error("未找到对应通道!");
              return;
            }
            that.getPlayback(res.data.data, startTime, endTime);
          });
      },
      getPlayback(data, startTime, endTime) {
        const that = this;
        const loading = this.$loading({
          lock: true,
          text: "正在加载中...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        that
          .$axios({
            method: "get",
            url: `/api/playback/start/${data.deviceId}/${data.channelId}?startTime=${startTime}&endTime=${endTime}`,
          })
          .then((res) => {
            loading.close();
            if (res.data.code != 0) {
              this.$message.error(res.data.msg);
              return;
            }
            window.open(res.data.data.fmp4, "_blank");
          });
      },
      clickVisibleImgae(item) {
        console.log(item);
        this.imageBase64 = this.domain + item.img_name;
        this.boxList = JSON.parse(item.params);
        this.dialogImgaeVisible = true;

        this.filePath = item.filePath ? this.videoDomain + item.filePath : "";
        this.alarmInfo = item
      },
      getToday() {
        const that = this;
        that
          .$axios({
            method: "get",
            url: `/api/message/today`,
          })
          .then((res) => {
            if (res.data.code == 0) {
              if (res.data.data != that.quantityNum && that.intervalShow) {
                that.$notify({
                  title: "提示",
                  duration: 5000,
                  dangerouslyUseHTMLString: true,
                  message: "您有最新提示信息，请注意查看",
                  position: "bottom-right",
                });
                that.tispShow = !that.tispShow;
                that.getLatest();
                setTimeout(() => {
                  that.tispShow = !that.tispShow;
                }, 5000);
              }
              this.quantityNum = res.data.data;
              return;
            }
            this.$message.error(res.data.msg);
          })
          .catch((error) => {
            console.log(error);
          });
      },
      getLatest() {
        const that = this;
        that
          .$axios({
            method: "get",
            url: `/api/message/latest`,
          })
          .then((res) => {
            if (res.data.code == 0) {
              this.alarmList = res.data.data;
              return;
            }
            this.$message.error(res.data.msg);
          })
          .catch((error) => {
            console.log(error);
          });
      },
      getALarmList() {
        const that = this;
        that
          .$axios({
            method: "get",
            url: `/api/message/list?page=${this.select.page}&count=${this.select.count}&beginTime=${this.select.date[0]}&endTime=${this.select.date[1]}`,
          })
          .then((res) => {
            if (res.data.code == 0) {
              this.alarmPopupList = res.data.data.list;
              this.select.total = res.data.data.total;
              return;
            }
            this.$message.error(res.data.msg);
          });
      },
      clickDialogImgae(img_name) {
        this.dialogImageShow = true;
        this.imgUrl = this.domain + img_name;
      },
      // 分页
      pagingDepartment(val) {
        this.select.page = val;
        this.getALarmList();
      },
    },
    beforeDestroy() {
      clearInterval(this.intervalId);
    },
  };
</script>

<style scoped>
  .state-btn {
    width: 40px;
    padding: 0;
    text-align: center;
    margin-left: 8px;
    font-size: 12px;
  }

  .alarm-select {
    margin-bottom: 20px;
    display: flex;
  }

  .paging-content {
    margin-top: 20px;
    text-align: right;
  }

  .alarm-popup {
    display: flex;
    flex-wrap: wrap;
    padding: 0 10px;
  }

  .alarm-popup .popup-item {
    width: 24%;
    margin: 0 0.5% 20px;
    height: auto;
    border-radius: 6px;
    overflow: hidden;
    padding-bottom: 10px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  }

  .alarm-popup .popup-item img {
    width: 100%;
    height: 200px;
  }

  .alarm-popup .popup-item .popup-title {
    font-weight: 500;
    font-size: 16px;
    color: #333;
    display: flex;
    margin-top: 8px;
    padding-left: 10px;
  }

  .alarm-popup .popup-item .popup-tips {
    font-size: 12px;
    line-height: 22px;
    display: flex;
    padding-left: 10px;
    color: #909399;
  }

  .alarm-content {
    margin-top: 50px;
  }

  .alarm-title {
    display: flex;
    font-weight: bold;
    font-size: 22px;
    color: #202b3d;
    padding-left: 10px;
    border-left: 4px solid #1890ff;
  }

  .alarm-card {
    width: 100%;
    height: 80px;
    border-radius: 6px;
    opacity: 0.8;
    /* background: url("~@static/images/download.jpg") no-repeat center;
  background-size: cover; */
    cursor: pointer;
    background: linear-gradient(135deg, #1890ff, #40a9ff, #66b1ff, #84c1ff);
    background-size: 600% 600%;
    animation: GradientAnimation 10s ease infinite;
    margin: auto;
    margin-top: 31px;
    margin-bottom: 34px;
    position: relative;
    display: flex;
    justify-content: space-between;
  }

  .alarm-card-error {
    background: linear-gradient(135deg, #ff1818, #ff4040, #ff6666, #ff8484);
  }

  @keyframes GradientAnimation {
    0% {
      background-position: 0% 50%;
    }

    50% {
      background-position: 100% 50%;
    }

    100% {
      background-position: 0% 50%;
    }
  }
  .alarm-container {
    height: calc(100vh - 250px);
    overflow-y: auto;
  }

  .alarm-card .text {
    font-size: 16px;
    color: #f5f5f5;
    padding: 10px 0 0 20px;
  }

  .alarm-card .text-right {
    color: #f5f5f5;
    font-size: 16px;
    padding: 30px 20px 0 0;
  }

  .alarm-tips {
    font-weight: 400;
    font-size: 18px;
    color: #202b3d;
    display: flex;
  }

  .alarm-item {
    border: 1px solid #eee;
    border-radius: 4px;
    padding-bottom: 10px;
    overflow: hidden;
    margin-bottom: 10px;
  }

  .alarm-item img {
    width: 100%;
    height: 120px;
  }

  .alarm-item .item-title {
    display: flex;
    margin-top: 4px;
    padding-left: 4px;
    color: #fff;
  }

  .alarm-item .item-tips {
    font-size: 12px;
    line-height: 20px;
    display: flex;
    padding-left: 4px;
  }

  .popup-video {
    color: #fff;
    font-size: 12px;
    line-height: 22px;
    display: flex;
    padding-left: 5px;
  }
</style>
